import os
import sys
import torch
import numpy as np
import gymnasium as gym
import torch.nn.functional as F
import matplotlib.pyplot as plt

from network import PolicyNet, ValueNet

sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import rl_utils


class ActorCritic:
    def __init__(
        self,
        state_dim,
        hidden_dim,
        action_dim,
        actor_lr,
        critic_lr,
        gamma,
        device,
    ):
        self.actor = PolicyNet(state_dim, hidden_dim, action_dim)
        self.critic = ValueNet(state_dim, hidden_dim)
        self.actor_optim = torch.optim.Adam(self.actor.parameters(), actor_lr)
        self.critic_optim = torch.optim.Adam(self.critic.parameters(), critic_lr)

        self.state_dim = state_dim
        self.gamma = gamma
        self.device = device

    def take_action(self, state):
        state = torch.tensor(np.array([state]), dtype=torch.float).to(self.device)
        probs = self.actor(state)
        dist = torch.distributions.Categorical(probs)
        action = dist.sample().item()
        return action

    def update(self, trans_dict):
        states = torch.tensor(trans_dict["states"], dtype=torch.float).to(self.device)
        actions = torch.tensor(trans_dict["actions"]).view(-1, 1).to(self.device)
        rewards = torch.tensor(trans_dict["rewards"], dtype=torch.float).view(-1, 1).to(self.device)
        next_states = torch.tensor(trans_dict["next_states"], dtype=torch.float).to(self.device)
        dones = torch.tensor(trans_dict["dones"], dtype=torch.float).view(-1, 1).to(self.device)

        # 计算 actor 的 loss
        td_target = rewards + self.gamma * self.critic(next_states) * (1 - dones)
        td_delta = td_target - self.critic(states)
        log_probs = torch.log(self.actor(states).gather(1, actions))
        actor_loss = torch.mean(-td_delta * log_probs)
        # actor 梯度下降
        self.actor_optim.zero_grad()
        actor_loss.backward()
        self.actor_optim.step()

        # 计算 critic 的 loss
        critic_loss = torch.mean(F.mse_loss(self.critic(states), td_target.detach()))
        self.critic_optim.zero_grad()
        critic_loss.backward()
        self.critic_optim.step()


if __name__ == "__main__":
    actor_lr = 1e-3
    critic_lr = 1e-2
    num_episodes = 1000
    hidden_dim = 128
    gamma = 0.98
    device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")

    env_name = "CartPole-v0"
    env = gym.make(env_name)
    env.reset(seed=0)
    torch.manual_seed(0)
    state_dim = env.observation_space.shape[0]
    action_dim = env.action_space.n
    agent = ActorCritic(state_dim, hidden_dim, action_dim, actor_lr, critic_lr, gamma, device)

    return_list = rl_utils.train_on_policy_agent(env, agent, num_episodes)

    episodes_list = list(range(len(return_list)))
    plt.plot(episodes_list, return_list)
    plt.xlabel("Episodes")
    plt.ylabel("Returns")
    plt.title("Actor-Critic on {}".format(env_name))
    plt.show()

    mv_return = rl_utils.moving_average(return_list, 9)
    plt.plot(episodes_list, mv_return)
    plt.xlabel("Episodes")
    plt.ylabel("Returns")
    plt.title("Actor-Critic on {}".format(env_name))
    plt.show()
